import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/routers/router_names.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/plan.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class StatisticPage extends StatefulWidget {
  const StatisticPage({super.key});

  @override
  State<StatisticPage> createState() => _StatisticPageState();
}

class _StatisticPageState extends State<StatisticPage> {
  List<Plan> _todayPlans = [];
  List<Plan> _yesterdayPlans = [];
  List<Plan> _dayBeforeYesterdayPlans = [];

  @override
  void initState() {
    super.initState();
    _loadPlanData();
  }

  void _loadPlanData() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      // 加载最近30天的计划，然后过滤出今天、昨天、前天的数据
      context.read<AwakBloc>().add(FetchLast30DaysPlansEvent(currentUser.id!));
    }
  }

  String _getCurrentMonthDateRange() {
    final now = DateTime.now();
    final firstDayOfMonth = DateTime(now.year, now.month, 1);
    final lastDayOfMonth = DateTime(now.year, now.month + 1, 0);
    
    final months = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];
    
    final monthName = months[now.month - 1];
    final startDay = firstDayOfMonth.day;
    final endDay = lastDayOfMonth.day;
    
    String getOrdinalSuffix(int day) {
      if (day >= 11 && day <= 13) {
        return 'th';
      }
      switch (day % 10) {
        case 1: return 'st';
        case 2: return 'nd';
        case 3: return 'rd';
        default: return 'th';
      }
    }
    
    return 'Data Record From $monthName ${startDay}${getOrdinalSuffix(startDay)} to $monthName ${endDay}${getOrdinalSuffix(endDay)}';
  }

  void _filterPlansByDate(List<Plan> allPlans) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(Duration(days: 1));
    final dayBeforeYesterday = today.subtract(Duration(days: 2));

    setState(() {
      _todayPlans = allPlans.where((plan) {
        final planStartDay = DateTime(plan.startTime.year, plan.startTime.month, plan.startTime.day);
        return planStartDay.year == today.year && 
               planStartDay.month == today.month && 
               planStartDay.day == today.day;
      }).toList();

      _yesterdayPlans = allPlans.where((plan) {
        final planStartDay = DateTime(plan.startTime.year, plan.startTime.month, plan.startTime.day);
        return planStartDay.year == yesterday.year && 
               planStartDay.month == yesterday.month && 
               planStartDay.day == yesterday.day;
      }).toList();

      _dayBeforeYesterdayPlans = allPlans.where((plan) {
        final planStartDay = DateTime(plan.startTime.year, plan.startTime.month, plan.startTime.day);
        return planStartDay.year == dayBeforeYesterday.year && 
               planStartDay.month == dayBeforeYesterday.month && 
               planStartDay.day == dayBeforeYesterday.day;
      }).toList();
    });
  }

  int _calculateTotalMinutes(List<Plan> plans) {
    int totalMinutes = 0;
    for (final plan in plans) {
      final duration = plan.endTime.difference(plan.startTime);
      totalMinutes += duration.inMinutes;
    }
    return totalMinutes;
  }

  int _calculateCompletedPlans(List<Plan> plans) {
    return plans.where((plan) => plan.state == 'completed').length;
  }

  String _getDayName(int daysAgo) {
    final now = DateTime.now();
    final targetDate = now.subtract(Duration(days: daysAgo));
    final weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return weekdays[targetDate.weekday - 1];
  }

  @override
  Widget build(BuildContext context) {
    final isTablet = DeviceUtils.isTablet(context);
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is Last30DaysPlansLoaded) {
          _filterPlansByDate(state.plans);
        }
      },
      child: Scaffold(
      body: Container(
        decoration: const BoxDecoration(color: Color(0xFF8B58F5)),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 16.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 50.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      textAlign: TextAlign.center,
                      'DATA STATISTICS',
                      style: AwakText.titleStyle.copyWith(color: Colors.white),
                    ),
                  ],
                ),
                SizedBox(height: 20.h),
                Container(
                  height: isTablet ? 200.h : 180.h,
                  width: double.infinity,
                  child: ListView.builder(
                    itemCount: 3,
                    scrollDirection: Axis.horizontal,
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      List<Plan> plans;
                      String dayName;
                      String dayTitle;
                      
                      switch (index) {
                        case 0:
                          plans = _todayPlans;
                          dayName = _getDayName(0);
                          dayTitle = 'Today\'s Goal';
                          break;
                        case 1:
                          plans = _yesterdayPlans;
                          dayName = _getDayName(1);
                          dayTitle = 'Yesterday\'s Goal';
                          break;
                        case 2:
                          plans = _dayBeforeYesterdayPlans;
                          dayName = _getDayName(2);
                          dayTitle = 'Day Before Yesterday';
                          break;
                        default:
                          plans = _todayPlans;
                          dayName = _getDayName(0);
                          dayTitle = 'Today\'s Goal';
                      }
                      
                      final totalPlans = plans.length;
                      final totalMinutes = _calculateTotalMinutes(plans);
                      final completedPlans = _calculateCompletedPlans(plans);
                      
                      return Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 14.h,
                        ),
                        margin: EdgeInsets.only(right: 12.w),
                        decoration: BoxDecoration(
                          color: const Color(0xFFD3F427),
                          borderRadius: BorderRadius.circular(16.r),
                          border: Border.all(color: Colors.black, width: 2.w),
                        ),
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Icon(
                                  AwakSvg.time,
                                  color: Colors.black,
                                  size: 20.sp,
                                ),
                                SizedBox(width: 8.w),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      dayTitle,
                                      style: AwakText.body16Style.copyWith(
                                        color: Colors.black,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      '$dayName Stats: The Following List',
                                      style: AwakText.body14Style.copyWith(
                                        color: Colors.black.withOpacity(0.7),
                                        fontSize: 10.sp,
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(width: 12.w),
                                GestureDetector(
                                  onTap: () {
                                    Beamer.of(context).beamToNamed(RouterNames.myPlan);
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 6.w,
                                      vertical: 4.h,
                                    ),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(8.r),
                                    ),
                                    child: Row(
                                      children: [
                                        Text(
                                          'MORE',
                                          style: AwakText.body16Style.copyWith(
                                            fontWeight: FontWeight.w500,
                                            fontSize: 12.sp,
                                          ),
                                        ),
                                        Icon(
                                          Icons.arrow_forward_ios,
                                          size: 10.w,
                                          color: Colors.black,
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 20.h),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  width: 69.w,
                                  height: isTablet ? 95.h : 85.h,
                                  padding: EdgeInsets.symmetric(
                                    vertical: isTablet ? 13.h : 14.h,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(8.r),
                                    border: Border.all(
                                      color: Colors.black,
                                      width: 2.w,
                                    ),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Text(
                                        '$totalPlans',
                                        style: AwakText.body16Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 20.sp,
                                        ),
                                      ),
                                      SizedBox(height: 6.h),
                                      Text(
                                        'Habit',
                                        style: AwakText.body14Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 12.sp,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(width: 12.w),
                                Container(
                                  width: 69.w,
                                  height: isTablet ? 95.h : 85.h,
                                  padding: EdgeInsets.symmetric(
                                    vertical: isTablet ? 13.h : 14.h,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(8.r),
                                    border: Border.all(
                                      color: Colors.black,
                                      width: 2.w,
                                    ),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Text(
                                        '$totalMinutes',
                                        style: AwakText.body16Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 20.sp,
                                        ),
                                      ),
                                      SizedBox(height: 6.h),
                                      Text(
                                        'Minute',
                                        style: AwakText.body14Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 12.sp,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(width: 12.w),
                                Container(
                                  width: 69.w,
                                  height: isTablet ? 95.h : 85.h,
                                  padding: EdgeInsets.symmetric(
                                    vertical: isTablet ? 13.h : 14.h,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(8.r),
                                    border: Border.all(
                                      color: Colors.black,
                                      width: 2.w,
                                    ),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Text(
                                        '$completedPlans',
                                        style: AwakText.body16Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 20.sp,
                                        ),
                                      ),
                                      SizedBox(height: 6.h),
                                      Text(
                                        'Complete',
                                        style: AwakText.body14Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 12.sp,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
                SizedBox(height: 20.h),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 22.h,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16.r),
                    border: Border.all(color: Colors.black, width: 2.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Icon(AwakSvg.index, color: Colors.black, size: 20.sp),
                          SizedBox(width: 8.w),
                          Text(
                            'Key Index',
                            style: AwakText.body16Style.copyWith(
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          Spacer(),
                          GestureDetector(
                            onTap: () {
                              Beamer.of(context).beamToNamed(RouterNames.myPlan);
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 6.w,
                                vertical: 4.h,
                              ),
                              decoration: BoxDecoration(
                                color: const Color(0xFFD3F427),
                                borderRadius: BorderRadius.circular(8.r),
                              ),
                              child: Row(
                                children: [
                                  Text(
                                    'MORE',
                                    style: AwakText.body16Style.copyWith(
                                      fontWeight: FontWeight.w500,
                                      fontSize: 12.sp,
                                    ),
                                  ),
                                  Icon(
                                    Icons.arrow_forward_ios,
                                    size: 10.w,
                                    color: Colors.black,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 28.w),
                        child: Row(
                          children: [
                            Text(
                              _getCurrentMonthDateRange(),
                              style: AwakText.body14Style.copyWith(
                                color: Colors.black.withOpacity(0.7),
                                fontWeight: FontWeight.w500,
                                fontSize: 10.sp,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 10.h),
                      Image.asset(
                        AwakImages.chart,
                        width: isTablet ? 300.w : 325.w,
                        height: isTablet ? 210.h : 201.h,
                        fit: BoxFit.cover,
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 20.h),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 22.h,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16.r),
                    border: Border.all(color: Colors.black, width: 2.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Icon(AwakSvg.medal, color: Colors.black, size: 20.sp),
                          SizedBox(width: 8.w),
                          Text(
                            'Medal',
                            style: AwakText.body16Style.copyWith(
                              color: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 28.w),
                        child: Row(
                          children: [
                            Text(
                              'Obtained medals can be shared in the community',
                              style: AwakText.body14Style.copyWith(
                                color: Colors.black.withOpacity(0.7),
                                fontWeight: FontWeight.w500,
                                fontSize: 10.sp,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 20.h),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(width: 2.w),
                          Column(
                            children: [
                              Image.asset(
                                AwakImages.medal1,
                                width: isTablet ? 88.w : 80.w,
                                height: isTablet ? 74.h : 55.h,
                                fit: BoxFit.cover,
                              ),
                              SizedBox(height: 10.h),
                              Text(
                                'Full Of Vitality',
                                style: AwakText.body14Style.copyWith(
                                  color: Colors.black,
                                  fontSize: 12.sp,
                                ),
                              ),
                            ],
                          ),

                          SizedBox(width: 2.w),
                          Column(
                            children: [
                              Image.asset(
                                AwakImages.medal2,
                                width: isTablet ? 88.w : 80.w,
                                height: isTablet ? 74.h : 55.h,
                                fit: BoxFit.cover,
                              ),
                              SizedBox(height: 10.h),
                              Text(
                                'July Challenge',
                                style: AwakText.body14Style.copyWith(
                                  color: Colors.black,
                                  fontSize: 12.sp,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(width: 2.w),
                          Column(
                            children: [
                              Image.asset(
                                AwakImages.medal3,
                                width: isTablet ? 88.w : 80.w,
                                height: isTablet ? 74.h : 55.h,
                                fit: BoxFit.cover,
                              ),
                              SizedBox(height: 10.h),
                              Text(
                                'Persistence',
                                style: AwakText.body14Style.copyWith(
                                  color: Colors.black,
                                  fontSize: 12.sp,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(width: 2.w),
                        ],
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 120.h),
              ],
            ),
          ),
        ),
      ),
    ));
  }
}
